package main

import (
	"fmt"
	"net/http"
	"time"

	"gitee.com/knowgo/ego"
	"gitee.com/knowgo/ego/egoc"
	"gitee.com/knowgo/ego/log"
	"golang.org/x/net/websocket"
)

type Abc struct{}

func (Abc) Group() egoc.Group {
	return egoc.Group{
		Name: "abc",
	}
}

func (Abc) Test(ctx *egoc.Context) (int, error) {
	ctx.UpgradeWebsocket(func(c *websocket.Conn) {
		var buf = make([]byte, 1024)
		n, _ := c.Read(buf)
		fmt.Printf("%s\n", buf[:n])
		for n := 0; n < 10; n++ {
			c.Write([]byte(fmt.Sprintf("%d", n)))
			time.Sleep(1 * time.Second)
		}

	}, true)
	return 0, nil
}

func main() {
	var log = log.NewLog()
	var eg = ego.NewWithLogger(log)
	eg.SetLogRequest(true).
		RegisterDcoApi()
	eg.Register(&Abc{})

	handle, err := eg.GetHandle()
	if err != nil {
		log.Errorf("create handle error: %s", err.Error())
		return
	}
	mux := &http.ServeMux{}
	mux.Handle("/api", handle)
	svr := &http.Server{
		Addr:    ":3000",
		Handler: mux,
	}
	svr.ListenAndServe()
}
